<template>
  <div class="waterfall-demo">
    <!-- 头部 -->
    <van-nav-bar
      title="瀑布流商品列表"
      left-arrow
      @click-left="$router.back()"
      class="demo-nav"
    />
    
    <!-- 功能控制面板 -->
    <div class="control-panel">
      <van-row gutter="12">
        <van-col span="12">
          <van-button
            type="primary"
            size="small"
            block
            @click="toggleSkeleton"
          >
            {{ showSkeleton ? '隐藏' : '显示' }}骨架屏
          </van-button>
        </van-col>
        <van-col span="12">
          <van-button
            type="success"
            size="small"
            block
            @click="changeColumns"
          >
            {{ columnCount }}列布局
          </van-button>
        </van-col>
      </van-row>
    </div>
    
    <!-- 瀑布流商品列表 -->
    <ProductWaterfallList
      ref="waterfallListRef"
      :products="products"
      :loading="loading"
      :has-more="hasMore"
      :column-count="columnCount"
      :show-skeleton="showSkeleton"
      :skeleton-count="6"
      :auto-load-more="true"
      @product-click="handleProductClick"
      @refresh="handleRefresh"
      @load-more="handleLoadMore"
      @retry="handleRetry"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { showToast, showDialog } from 'vant'
import ProductWaterfallList from '@/components/ProductWaterfallList.vue'
import type { ProductItem } from '@/components/ProductWaterfallCard.vue'

// 响应式数据
const waterfallListRef = ref<InstanceType<typeof ProductWaterfallList>>()
const products = ref<ProductItem[]>([])
const loading = ref(false)
const hasMore = ref(true)
const showSkeleton = ref(false)
const columnCount = ref(2)
const currentPage = ref(1)
const pageSize = ref(20)

// 生命周期
onMounted(() => {
  loadInitialData()
})

// 方法
async function loadInitialData(): Promise<void> {
  loading.value = true
  showSkeleton.value = true
  
  try {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    const newProducts = generateMockProducts(pageSize.value)
    products.value = newProducts
    currentPage.value = 1
    hasMore.value = true
  } catch (error) {
    console.error('加载数据失败:', error)
    showToast('加载失败，请重试')
  } finally {
    loading.value = false
    showSkeleton.value = false
  }
}

async function handleRefresh(): Promise<void> {
  try {
    // 模拟刷新延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const newProducts = generateMockProducts(pageSize.value)
    products.value = newProducts
    currentPage.value = 1
    hasMore.value = true
    
    showToast('刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    showToast('刷新失败，请重试')
  }
}

async function handleLoadMore(): Promise<void> {
  if (loading.value || !hasMore.value) return
  
  loading.value = true
  
  try {
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    currentPage.value++
    
    // 模拟没有更多数据
    if (currentPage.value > 5) {
      hasMore.value = false
      showToast('没有更多商品了')
      return
    }
    
    const newProducts = generateMockProducts(pageSize.value)
    products.value.push(...newProducts)
    
    showToast(`加载了 ${newProducts.length} 个商品`)
  } catch (error) {
    console.error('加载更多失败:', error)
    showToast('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

function handleProductClick(product: ProductItem): void {
  showDialog({
    title: '商品详情',
    message: `
      商品名称：${product.title}
      商品价格：¥${product.price}
      销量：${product.sales}
      ${product.rating ? `评分：${product.rating}` : ''}
    `,
    confirmButtonText: '知道了'
  })
}

function handleRetry(): void {
  loadInitialData()
}

function toggleSkeleton(): void {
  showSkeleton.value = !showSkeleton.value
}

function changeColumns(): void {
  columnCount.value = columnCount.value === 2 ? 3 : 2
  showToast(`切换到${columnCount.value}列布局`)
}

// 生成模拟商品数据
function generateMockProducts(count: number): ProductItem[] {
  const products: ProductItem[] = []
  const categories = ['数码', '服装', '家居', '美妆', '食品', '运动', '图书', '玩具']
  const brands = ['Apple', 'Samsung', 'Nike', 'Adidas', 'Zara', 'H&M', 'IKEA', 'MUJI']
  const tags = ['热销', '新品', '限时', '包邮', '特价', '推荐']
  
  for (let i = 0; i < count; i++) {
    const id = Date.now() + Math.random()
    const category = categories[Math.floor(Math.random() * categories.length)]
    const brand = brands[Math.floor(Math.random() * brands.length)]
    const price = Math.floor(Math.random() * 1000) + 10
    const originalPrice = Math.random() > 0.7 ? price + Math.floor(Math.random() * 200) + 50 : undefined
    const sales = Math.floor(Math.random() * 10000)
    const rating = Math.random() > 0.3 ? Number((Math.random() * 2 + 3).toFixed(1)) : undefined
    const productTags = Math.random() > 0.5 ? 
      tags.sort(() => 0.5 - Math.random()).slice(0, Math.floor(Math.random() * 3) + 1) : 
      undefined
    
    products.push({
      id,
      title: `${brand} ${category}商品 ${i + 1 + (currentPage.value - 1) * pageSize.value}`,
      image: `https://picsum.photos/300/${Math.floor(Math.random() * 200) + 200}?random=${id}`,
      price,
      originalPrice,
      sales,
      rating,
      tags: productTags
    })
  }
  
  return products
}
</script>

<style scoped>
.waterfall-demo {
  min-height: 100vh;
  background: #f5f5f5;
}

.demo-nav {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.control-panel {
  padding: 12px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 46px;
  z-index: 10;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .control-panel {
    padding: 10px;
  }
}
</style>